package com.geek.water.controller;

import com.geek.water.entity.CollectionStrategy;
import com.geek.water.result.Result;
import com.geek.water.service.CollectionStrategyService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 催缴提醒控制器
 */
@RestController
@RequestMapping("/api/collection-reminder")
public class CollectionReminderController {

    @Autowired
    private CollectionStrategyService collectionStrategyService;

    /**
     * 获取逾期账单列表
     */
    @GetMapping("/overdue-bills")
    public Result getOverdueBills(
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "10") Integer pageSize,
            @RequestParam(required = false) String customerName,
            @RequestParam(required = false) String overdueDays,
            @RequestParam(required = false) String notifyStatus) {

        // 模拟数据
        List<Map<String, Object>> bills = new ArrayList<>();

        Map<String, Object> bill1 = new HashMap<>();
        bill1.put("id", 1);
        bill1.put("bill_code", "BILL202401001");
        bill1.put("customer_name", "测试客户1");
        bill1.put("amount", 1500.00);
        bill1.put("overdue_days", 15);
        bill1.put("strategy_name", "15天逾期提醒");
        bill1.put("status", "pending");
        bill1.put("scheduled_at", "2024-01-15 10:00:00");
        bill1.put("sent_at", null);
        bills.add(bill1);

        Map<String, Object> bill2 = new HashMap<>();
        bill2.put("id", 2);
        bill2.put("bill_code", "BILL202401002");
        bill2.put("customer_name", "测试客户2");
        bill2.put("amount", 2300.00);
        bill2.put("overdue_days", 8);
        bill2.put("strategy_name", "7天逾期提醒");
        bill2.put("status", "pending");
        bill2.put("scheduled_at", "2024-01-10 14:30:00");
        bill2.put("sent_at", null);
        bills.add(bill2);

        Map<String, Object> result = new HashMap<>();
        result.put("list", bills);
        result.put("total", bills.size());

        return new Result(com.geek.water.constant.CodeConstant.SUCCESS, "获取成功", result);
    }

    /**
     * 发送催缴通知
     */
    @PostMapping("/send-notification")
    public Result sendNotification(@RequestBody Map<String, Object> request) {
        // 安全地获取billId，支持多种类型
        Object billIdObj = request.get("billId");
        String billId = billIdObj != null ? billIdObj.toString() : null;

        Object channelsObj = request.get("channels");
        String channels = channelsObj != null ? channelsObj.toString() : null;

        // 这里应该调用实际的通知发送服务
        System.out.println("发送催缴通知 - 账单ID: " + billId + ", 渠道: " + channels);

        return new Result(com.geek.water.constant.CodeConstant.SUCCESS, "通知发送成功");
    }

    /**
     * 获取催缴统计信息
     */
    @GetMapping("/stats")
    public Result getCollectionStats() {
        Map<String, Object> stats = new HashMap<>();
        stats.put("totalOverdue", 10);
        stats.put("totalAmount", 15000.00);
        stats.put("sentCount", 8);
        stats.put("paidCount", 2);
        stats.put("overdue1to7", 3);
        stats.put("overdue8to15", 4);
        stats.put("overdue16to30", 2);
        stats.put("overdue30plus", 1);

        return new Result(com.geek.water.constant.CodeConstant.SUCCESS, "获取成功", stats);
    }

    /**
     * 批量发送催缴通知
     */
    @PostMapping("/batch-send")
    public Result batchSendNotifications(@RequestBody Map<String, Object> request) {
        // 安全地获取billIds，支持多种类型
        Object billIdsObj = request.get("billIds");
        List<String> billIds = new ArrayList<>();
        if (billIdsObj instanceof List) {
            for (Object item : (List<?>) billIdsObj) {
                if (item != null) {
                    billIds.add(item.toString());
                }
            }
        }

        Object channelsObj = request.get("channels");
        String channels = channelsObj != null ? channelsObj.toString() : null;

        // 这里应该调用实际的批量通知发送服务
        System.out.println("批量发送催缴通知 - 账单数量: " + billIds.size() + ", 渠道: " + channels);

        return new Result(com.geek.water.constant.CodeConstant.SUCCESS, "成功发送 " + billIds.size() + " 条催缴通知");
    }

    /**
     * 获取催缴策略
     */
    @GetMapping("/policies")
    public Result getCollectionPolicies() {
        try {
            List<CollectionStrategy> strategies = collectionStrategyService.getAllStrategies();
            return new Result(com.geek.water.constant.CodeConstant.SUCCESS, "获取成功", strategies);
        } catch (Exception e) {
            return new Result(com.geek.water.constant.CodeConstant.FAIL, "获取催缴策略失败: " + e.getMessage());
        }
    }

    /**
     * 创建催缴策略
     */
    @PostMapping("/policies")
    public Result createCollectionPolicy(@RequestBody Map<String, Object> policy) {
        try {
            CollectionStrategy strategy = new CollectionStrategy();
            strategy.setStrategyName((String) policy.get("strategy_name"));
            strategy.setDaysOverdue((Integer) policy.get("days_overdue"));
            strategy.setNotificationChannels((String) policy.get("notification_channels"));
            strategy.setPriority((Integer) policy.get("priority"));
            strategy.setIsActive((Boolean) policy.get("is_active"));

            boolean success = collectionStrategyService.createStrategy(strategy);
            if (success) {
                return new Result(com.geek.water.constant.CodeConstant.SUCCESS, "策略创建成功");
            } else {
                return new Result(com.geek.water.constant.CodeConstant.FAIL, "策略创建失败");
            }
        } catch (Exception e) {
            return new Result(com.geek.water.constant.CodeConstant.FAIL, "策略创建失败: " + e.getMessage());
        }
    }

    /**
     * 更新催缴策略
     */
    @PutMapping("/policies/{id}")
    public Result updateCollectionPolicy(
            @PathVariable Long id,
            @RequestBody Map<String, Object> policy) {
        try {
            CollectionStrategy strategy = new CollectionStrategy();
            strategy.setId(id);
            strategy.setStrategyName((String) policy.get("strategy_name"));
            strategy.setDaysOverdue((Integer) policy.get("days_overdue"));
            strategy.setNotificationChannels((String) policy.get("notification_channels"));
            strategy.setPriority((Integer) policy.get("priority"));
            strategy.setIsActive((Boolean) policy.get("is_active"));

            boolean success = collectionStrategyService.updateStrategy(strategy);
            if (success) {
                return new Result(com.geek.water.constant.CodeConstant.SUCCESS, "策略更新成功");
            } else {
                return new Result(com.geek.water.constant.CodeConstant.FAIL, "策略更新失败");
            }
        } catch (Exception e) {
            return new Result(com.geek.water.constant.CodeConstant.FAIL, "策略更新失败: " + e.getMessage());
        }
    }

    /**
     * 删除催缴策略
     */
    @DeleteMapping("/policies/{id}")
    public Result deleteCollectionPolicy(@PathVariable Long id) {
        try {
            System.out.println("开始删除策略，ID: " + id);

            // 检查策略是否存在
            CollectionStrategy existingStrategy = collectionStrategyService.getById(id);
            if (existingStrategy == null) {
                System.out.println("策略不存在，ID: " + id);
                return new Result(com.geek.water.constant.CodeConstant.FAIL, "策略不存在");
            }

            System.out.println("找到策略: " + existingStrategy.getStrategyName());

            // 检查策略是否被使用
            boolean isUsed = collectionStrategyService.isStrategyUsed(id);
            System.out.println("策略使用状态检查结果: " + isUsed);

            if (isUsed) {
                System.out.println("策略正在使用中，无法删除");
                return new Result(com.geek.water.constant.CodeConstant.FAIL, "策略正在使用中，无法删除");
            }

            System.out.println("开始执行删除操作...");
            boolean success = collectionStrategyService.removeById(id);
            System.out.println("删除操作结果: " + success);

            if (success) {
                System.out.println("策略删除成功");
                return new Result(com.geek.water.constant.CodeConstant.SUCCESS, "策略删除成功");
            } else {
                System.out.println("策略删除失败");
                return new Result(com.geek.water.constant.CodeConstant.FAIL, "策略删除失败");
            }
        } catch (Exception e) {
            System.out.println("删除策略时发生异常: " + e.getMessage());
            e.printStackTrace();
            return new Result(com.geek.water.constant.CodeConstant.FAIL, "策略删除失败: " + e.getMessage());
        }
    }

    /**
     * 生成催缴任务
     */
    @PostMapping("/generate-tasks")
    public Result generateCollectionTasks() {
        // 这里应该调用实际的服务生成催缴任务
        // 根据逾期账单和催缴策略自动生成通知任务

        System.out.println("生成催缴任务");

        return new Result(com.geek.water.constant.CodeConstant.SUCCESS, "成功生成催缴任务");
    }

    /**
     * 确认催缴任务
     */
    @PostMapping("/confirm-task")
    public Result confirmCollectionTask(@RequestBody Map<String, Object> request) {
        // 安全地获取taskId，支持多种类型
        Object taskIdObj = request.get("taskId");
        String taskId = taskIdObj != null ? taskIdObj.toString() : null;

        // 这里应该调用实际的服务确认任务
        System.out.println("确认催缴任务 - 任务ID: " + taskId);

        return new Result(com.geek.water.constant.CodeConstant.SUCCESS, "任务确认成功");
    }
}
